package com.gitee.feizns.webtemplate.commons.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 请求
 * @author feizns
 * @since 2019/4/12
 */
public abstract class RequestUtils {

    /**
     * 所有需要处理的代理请求头
     */
    private static final String[] HEADERS = { "x-forwarded-for", "Proxy-Client-IP", "WL-Proxy-Client-IP",
            "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR", "X-Real-IP" };

    /**
     * 获取用户真实ip
     * @link https://www.cnblogs.com/xiaoxing/p/6565573.html
     * @return
     */
    public static String getIpAddress() {
        HttpServletRequest req = getRequest();
        for (String header : HEADERS) {
            String val = req.getHeader(header);
            if ( ipValidate(val) )
                return val.split(",")[0];
        }
        return req.getRemoteAddr();
    }

    private static boolean ipValidate(String val) {
        return val != null
                && val.length() != 0
                && "unknown".equalsIgnoreCase(val) == false;
    }

    /**
     * 获取
     * @return
     */
    public static String getUserAgent() {
        return getRequest().getHeader("User-Agent");
    }

    /**
     * 获取token
     * @return
     */
    public static String getToken() {
        return getRequest().getHeader("token");
    }

    /**
     * 获取请求
     * @return
     */
    public static final HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 获取当前服务器地址
     * @return
     */
    public static String getBasePath() {
        HttpServletRequest req = getRequest();
        StringBuilder result = new StringBuilder(req.getScheme());
        return result.append("://")
                .append(req.getServerName())
                .append(req.getServerPort() == 80 ? "" : ":" + req.getServerPort())
                .append(req.getContextPath()).toString();
    }

    /**
     * 获取web资源
     * @param dir
     * @return
     */
    public static String getRealPath(String dir) {
        return RequestUtils.getRequest().getServletContext().getRealPath(dir);
    }

}
